package com.jzoffer;

public class MergeTwoList {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(5);
        ListNode l2 = new ListNode(9);
        ListNode l3 = new ListNode(49);
        ListNode l4 = new ListNode(79);
        ListNode l5 = new ListNode(3249);

        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;

        ListNode l11 = new ListNode(2);
        ListNode l22 = new ListNode(10);
        ListNode l33 = new ListNode(34);
        ListNode l44 = new ListNode(80);
        ListNode l55 = new ListNode(467);
        ListNode l66 = new ListNode(100000);

        l11.next = l22;
        l22.next = l33;
        l33.next = l44;
        l44.next = l55;
        l55.next = l66;

        ListNode res = Merge(l1,l11);
        while (res != null){
            System.out.println(res.val);
            res = res.next;
        }

    }

    public static ListNode Merge(ListNode list1,ListNode list2){
        if(list1 == null && list2 == null){
            return null;
        }
        if(list1 == null){
            return list2;
        }
        if(list2 == null){
            return list1;
        }

        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;

        while (list1 != null && list2 != null){
            if(list1.val <= list2.val){
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }else{
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }

        if(list1 != null){
            cur.next = list1;
        }
        if(list2 != null){
            cur.next = list2;
        }
        return dummy.next;

    }
}
